import c from '../colors';
import { runTask } from '../common';
import type { Config } from '../definitions';
import { logSuccess } from '../log';
import type { RunCommandOptions } from '../tasks/run';
import { runCommand } from '../util/subprocess';

export async function runOhos(config: Config, runOptions: RunCommandOptions): Promise<void> {
  try {
    // 首先构建项目
    await runTask('Building HarmonyOS project', async () =>
      runCommand('hvigor', ['build'], {
        cwd: config.ohos.platformDirAbs,
      }),
    );

    // 然后安装到设备
    if (runOptions.target) {
      await runTask(`Installing to device: ${runOptions.target}`, async () =>
        runCommand('hdc', ['install', '-r', 'entry/build/default/outputs/default/entry-default-signed.hap'], {
          cwd: config.ohos.platformDirAbs,
        }),
      );
      
      logSuccess(`HarmonyOS app installed and running on ${runOptions.target}!`);
    } else {
      // 如果没有指定目标设备，列出可用设备
      await runTask('Listing available devices', async () =>
        runCommand('hdc', ['list', 'targets'], {
          cwd: config.ohos.platformDirAbs,
        }),
      );
      
      logSuccess('HarmonyOS build completed. Use --target to specify a device for installation.');
    }
  } catch (e) {
    if ((e as any).includes('ENOENT')) {
      throw `HarmonyOS development tools not found. Please ensure HarmonyOS SDK is properly installed and hvigor/hdc are in your PATH. ${c.strong(
        'Download DevEco Studio: https://developer.harmonyos.com/cn/develop/deveco-studio'
      )}`;
    } else {
      throw new Error(`HarmonyOS run failed: ${e}`);
    }
  }
}